import { isUndefined, isArray, _pick, reduceToObject, randomNumber } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import pageMW from "../../middleware/pager";
import Router from "koa-router";
import {
  doCheckIn1,
  getCheckIn1,
} from "../../service/activityUserProcedureService";
import { listActivityUserAwardsByActivityIDAndUserIDAndAwardType } from "../../service/activityUserAwardService";
import { isAwardType } from "../../bg-enums/awardType";

const router = new Router();

// 获取签到信息(用户视角)
router.get("/usr/checkIn1/fetch/:brandId", async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { userId } = ctx;
  const checkIn1 = await getCheckIn1(brandId, userId);
  ctx.body = {
    ...checkIn1,
  };
});

// 签到1
router.post("/usr/checkIn1/do", async (ctx: AppCTX, next) => {
  const { activityId, authorizeNextRemind } = ctx.request.body;
  const { userId, userOpenId } = ctx;
  let awardInfos = await doCheckIn1({
    activityId,
    userId,
    userOpenId,
    authorizeNextRemind: !!authorizeNextRemind,
  });
  ctx.body = {
    awardInfos,
  };
});

// 获取用户签到1的奖励列表
router.get("/usr/checkIn1/awards", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { activityId, awardType } = ctx.query;

  if (isUndefined(awardType)) {
    ctx.throw(400, "awardType missing");
  }
  if (!isAwardType(awardType)) {
    ctx.throw(400, "awardType invalid");
  }

  const {
    total,
    items,
  } = await listActivityUserAwardsByActivityIDAndUserIDAndAwardType(
    {
      activityId,
      userId,
      awardType,
    },
    {
      limit,
      offset,
      ts,
    }
  );
  ctx.body = {
    total,
    rows: items,
  };
});

export default router;
